package com.moli.iov.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  token工具类
 * </p>
 *
 * @author zql
 * @since 2019/8/12 11:56
 */
public class TokenUtil {

	/**
	 * JWT token 盐
	 */
	private static final String SALT = "d6697c23-c49f-400d-bffd-6ea4120ba2bf";

	/**
	 * 生成用户token
	 * @return
	 */
	public static String createToken(){
		return createUUID();
	}


	/**
	 * 生成uuid
	 * @return
	 */
	public static String createUUID(){
		String uuid = UUID.randomUUID().toString();
		return uuid;
	}

	/**
	 * JWT生成token
	 * @param map
	 * @param expirationTime
	 * @return
	 */
	public static String createJWT(Map<String, String> map, Long expirationTime){
		return createJWT(map, SALT, expirationTime);
	}

	/**
	 * JWT生成token
	 * @param map
	 * @param salt
	 * @return
	 */
	public static String createJWT(Map<String, String> map, String salt, Long expirationTime){
		JwtBuilder jwtBuilder = Jwts.builder()
									.signWith(SignatureAlgorithm.HS256, salt)
									.setIssuedAt(new Date())
									.setExpiration(new Date(System.currentTimeMillis() + expirationTime));

		for(Map.Entry<String, String> entry : map.entrySet()){
			jwtBuilder.claim(entry.getKey(), entry.getValue());
		}

		return jwtBuilder.compact();
	}

	/**
	 * 解析token
	 * @param token
	 * @param salt
	 * @return
	 */
	public static Claims jwtParser(String token, String salt){
		try{
			Claims claims = Jwts.parser()
					.setSigningKey(salt)
					.parseClaimsJws(token)
					.getBody();

			return claims;
		}catch(Exception e){
			return null;
		}
	}
}
